package com.efivestar.idm.api.config.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import com.efivestar.idm.api.util.spring.SpringUtils;
import com.efivestar.idm.api.util.weixin.ContextHolder;
import com.efivestar.idm.api.util.weixin.WeixinApi;
import com.efivestar.idm.api.util.weixin.bean.WeiXinOAuth2ScopeEnum;
import com.efivestar.idm.api.util.weixin.bean.WeiXinUser;

@Configuration
@Order(1)
@WebFilter(filterName = "userInfoFilter", urlPatterns = "/*")
public class UserInfoFilter implements Filter {

    @Autowired
    private Environment env;

    @Autowired
    private WeixinApi weixinApi;

    @Value("${service.domain:51ai.cc}")
    private String domain;

    private static final String OID_COOKIE_NAME = "oid";
    private static final String OID_SIGNATURE_COOKIE_NAME = "sign";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        try {
            String excludePattern = SpringUtils.getStaticFilePatterns() + env.getProperty("userInfoFilter.exclude-pattern");
            WeiXinUser.WeiXinUserBuilder builder = WeiXinUser.builder();
            //当前url必须要有openId.
            String[] excludePatterns = excludePattern.split(",");
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            //当前url不需要获取openId信息.
            boolean isExcludeUrl = false;
            if (excludePatterns != null) {
                for (String pattern : excludePatterns) {
                    boolean match = antPathMatcher.match(pattern, getRequestPath(request));
                    if (match) {
                        isExcludeUrl = true;
                        break;
                    }
                }
            }

            if (!isExcludeUrl) {
                //设置微信的用户信息到线程中.
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        String cookieName = cookie.getName();
                        String cookieValue = cookie.getValue();
                        if (OID_COOKIE_NAME.equalsIgnoreCase(cookieName)) {
                            builder.openId(cookieValue);
                        } else if (OID_SIGNATURE_COOKIE_NAME.equalsIgnoreCase(cookieName)) {
                            builder.signature(cookieValue);
                        }
                    }
                }
                WeiXinUser weixinUser = builder.build();
                //当前地址没有携带openId
                if (StringUtils.isEmpty(weixinUser.getOpenId()) || StringUtils.isEmpty(weixinUser.getSignature())) {
                    String returnOpenIdUrl = weixinApi.getOAuth2AccessTokenUrl("http://"+ domain +"/getOpenId?redirectUrl=http://"+domain + getRequestPath(request), WeiXinOAuth2ScopeEnum.SNSAPI_BASE, "123");
                    response.sendRedirect(returnOpenIdUrl);
                    return;
                }
                ContextHolder.putWeixinUser(weixinUser);
            }
            filterChain.doFilter(servletRequest,servletResponse);
        } finally {
            //清除线程绑定中的微信用户信息
            ContextHolder.removeWeixinUser();
        }
    }

    /**
     * 获取当前的访问路径
     * @param request
     * @return
     */
    private String getRequestPath(HttpServletRequest request) {
        String url = request.getServletPath();
        if (request.getPathInfo() != null) {
            url += request.getPathInfo();
        }
        return url;
    }


    @Override
    public void destroy() {

    }
}